package com.newthread.android.util;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.view.View;
import android.widget.ImageView;
import com.newthread.android.R;
import com.nostra13.universalimageloader.cache.disc.impl.UnlimitedDiscCache;
import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.SimpleImageLoadingListener;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;

import java.io.File;
import java.math.BigDecimal;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

/**
 * Created by jindongping on 15/6/5.
 */
public class ImageUtil {
    private ImageLoader imageLoader;
    private volatile static ImageUtil instance;

    public static ImageUtil getInstance(Context context) {
        if (instance == null) {
            synchronized (ImageUtil.class) {
                if (instance == null) {
                    instance = new ImageUtil(context);
                }
            }
        }
        return instance;
    }

    //初始化ImageLoaderConfig
    private ImageLoaderConfiguration initImageLoaderConfig(Context context) {
        File cache = FileUtil.CreateDirIfNotExit("/Caches/");
        return new ImageLoaderConfiguration.Builder(context)
                .discCache(new UnlimitedDiscCache(cache, new Md5FileNameGenerator()))
                .build();
    }

    protected ImageUtil(Context context) {
        imageLoader = ImageLoader.getInstance();
        imageLoader.init(initImageLoaderConfig(context));
    }

    private DisplayImageOptions CreateDImgOptions() {
        return new DisplayImageOptions.Builder()
                .showStubImage(R.drawable.camera_btn_nor)          // 设置图片下载期间显示的图片
                .showImageForEmptyUri(R.drawable.camera_btn_nor)  // 设置图片Uri为空或是错误的时候显示的图片
                .showImageOnFail(R.drawable.camera_btn_nor)       // 设置图片加载或解码过程中发生错误显示的图片
                .cacheInMemory(true)                        // 设置下载的图片是否缓存在内存中
                .cacheOnDisc(true)                          // 设置下载的图片是否缓存在SD卡中
                .bitmapConfig(Bitmap.Config.RGB_565)        //因为默认是ARGB_8888， 使用RGB_565会比使用ARGB_8888少消耗2倍的内存
                .displayer(new RoundedBitmapDisplayer(20))  // 设置成圆角图片
                .build();
    }

    public void disPalyImage(String uri, ImageView imageView) {
        imageLoader.displayImage(uri, imageView, CreateDImgOptions(), new AnimateFirstDisplayListener());
    }

    private static class AnimateFirstDisplayListener extends SimpleImageLoadingListener {
        static final List<String> displayedImages = Collections.synchronizedList(new LinkedList<String>());

        @Override
        public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
            if (loadedImage != null) {
                ImageView imageView = (ImageView) view;
                // 是否第一次显示
                boolean firstDisplay = !displayedImages.contains(imageUri);
                if (firstDisplay) {
                    // 图片淡入效果
                    FadeInBitmapDisplayer.animate(imageView, 500);
                    displayedImages.add(imageUri);
                }
            }
        }
    }


    public Bitmap autoFilterPhoto(String bitmapPath) {
        Bitmap bitmap = compressImageFromFile(bitmapPath);
        if (bitmap.getWidth() < 500) {
            bitmap = big(bitmap, true);
        } else if (bitmap.getHeight() < 500) {
            bitmap = big(bitmap, false);
        }
        return bitmap;
    }

    /**
     * 缩小算法
     *
     * @param srcPath
     * @return
     */
    public Bitmap compressImageFromFile(String srcPath) {
        BitmapFactory.Options newOpts = new BitmapFactory.Options();
        newOpts.inJustDecodeBounds = true;//只读边,不读内容
        Bitmap bitmap = BitmapFactory.decodeFile(srcPath, newOpts);
        newOpts.inJustDecodeBounds = false;
        int w = newOpts.outWidth;
        int h = newOpts.outHeight;
        float hh = 800f;//
        float ww = 480f;//
        int be = 1;
        if (w > h && w > ww) {
            be = (int) (newOpts.outWidth / ww);
        } else if (w < h && h > hh) {
            be = (int) (newOpts.outHeight / hh);
        }
        if (be <= 0)
            be = 1;
        newOpts.inSampleSize = be;//设置采样率

        newOpts.inPreferredConfig = Bitmap.Config.ARGB_8888;//该模式是默认的,可不设
        newOpts.inPurgeable = true;// 同时设置才会有效
        newOpts.inInputShareable = true;//。当系统内存不够时候图片自动被回收

        bitmap = BitmapFactory.decodeFile(srcPath, newOpts);
        return bitmap;
    }


    /**
     * 压缩图片
     *
     * @param bitmap   源图片
     * @param width    想要的宽度
     * @param height   想要的高度
     * @param isAdjust 是否自动调整尺寸, true图片就不会拉伸，false严格按照你的尺寸压缩
     * @return Bitmap
     */
    public Bitmap reduce(Bitmap bitmap, int width, int height, boolean isAdjust) {
        // 如果想要的宽度和高度都比源图片小，就不压缩了，直接返回原图
        if (bitmap.getWidth() < width && bitmap.getHeight() < height) {
            return bitmap;
        }
        // 根据想要的尺寸精确计算压缩比例, 方法详解：public BigDecimal divide(BigDecimal divisor, int scale, int roundingMode);
        // scale表示要保留的小数位, roundingMode表示如何处理多余的小数位，BigDecimal.ROUND_DOWN表示自动舍弃
        float sx = new BigDecimal(width).divide(new BigDecimal(bitmap.getWidth()), 4, BigDecimal.ROUND_DOWN).floatValue();
        float sy = new BigDecimal(height).divide(new BigDecimal(bitmap.getHeight()), 4, BigDecimal.ROUND_DOWN).floatValue();
        if (isAdjust) {// 如果想自动调整比例，不至于图片会拉伸
            sx = (sx < sy ? sx : sy);
            sy = sx;// 哪个比例小一点，就用哪个比例
        }
        Matrix matrix = new Matrix();
        matrix.postScale(sx, sy);// 调用api中的方法进行压缩，就大功告成了
        return Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
    }

    public Bitmap big(Bitmap bitmap, boolean isWidth) {
        int bmpWidth = bitmap.getWidth();
        int bmpHeight = bitmap.getHeight();
        /* 设置图片放大的比例 */
        double needScaleW = 1;
        double needScaleH = 1;
        /* 计算这次要放大的比例 */
        float scaleWidth = 1;
        float scaleHeight = 1;
        if (isWidth) {
            needScaleW = 500 / bitmap.getWidth();

            scaleWidth = (float) (scaleWidth * needScaleW);
            scaleHeight = (float) (scaleHeight * needScaleW);
        } else {
            needScaleH = 500 / bitmap.getHeight();
            scaleWidth = (float) (scaleWidth * needScaleH);
            scaleHeight = (float) (scaleHeight * needScaleH);
        }
        /* 产生reSize后的Bitmap对象 */
        Matrix matrix = new Matrix();
        matrix.postScale(scaleWidth, scaleHeight);
        return Bitmap.createBitmap(bitmap, 0, 0, bmpWidth, bmpHeight, matrix, true);
    }


}
